package com.jt.zcdemo.interceptor;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jt.zcdemo.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class WebSocketInterceptor  implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info("---------握手开始---------");
        log.info("访问路径:"+request.getURI());
        boolean flag = false;
        // 获得请求参数
        HashMap<String, String> paramMap = (HashMap<String, String>) HttpUtil.decodeParamMap(request.getURI().getQuery(), CharsetUtil.CHARSET_UTF_8);
        String token = paramMap.get("token");
        if(token != null && !"".equals(token)) {
            //验证token
            //String adminId = stringRedisTemplate.opsForValue().get(token);
            if (StrUtil.isNotBlank(token)) {
               // String realToken = stringRedisTemplate.opsForValue().get(adminId);
                flag =  true;
            }
        }
        response.getHeaders().setContentType(new MediaType("application","json", Charset.forName("UTF-8")));
        if (!flag) {
            log.info("用户未登录");

            Result result = new Result();

            result.setCode("1001");
            result.setMessage("用户未登陆");

            response.getBody().write(JSON.toJSONBytes(request));
        }
        return flag;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

        log.info("握手成功...");
        try {

            Result result = new Result();
            result.setCode("1000");
            result.setMessage("WebSocket连接成功！");

            response.getBody().write(JSON.toJSONBytes(result));
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}
